package FIT::TypeAdapter::ArrayRef;

use FIT::Class;
use Moose::Util::TypeConstraints;
use aliased 'FIT::Document::Parser::Text';
extends 'FIT::TypeAdapter::Base';

my $SPLIT_CHAR = ',';

# TODO: support lists and nested tables
sub parse {
    my $cell = shift;
    local $_;
    my $text = $cell->trimmed_text;
    my @parts =
        map { $self->child_parse_from_string( Text->html_to_text($_) ) }
        split /\s*$SPLIT_CHAR\s*/,
        $text;
    $self->validate(\@parts);
    return \@parts;
}

sub as_string {
    my ($actual, $expected, $result, $cell) = @_;
    local $_;
    return join "$SPLIT_CHAR ", map {
        s/,/\\,/g;
        s/\\/\\\\/g;
        $self->child_as_string($_);
    } @{ $actual };
}

sub compare {
    my ($actual, $expected) = @_;
    return $self->SUPER::compare($actual, $expected)
        if !defined($actual) || !defined($expected);
    return 0 unless @$actual == @$expected;
    my $count = @$actual - 1;
    for my $i (0..$count) {
        my $actual_e   = $actual->[$i];
        my $expected_e = $expected->[$i];
        return 0 unless $self->child_compare($actual_e, $expected_e);
    }
    return 1;
}

